package com.zmh.service.http;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties.Couchbase;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.zmh.common.DateUtil;
import com.zmh.common.HtmlUtil;
import com.zmh.dao.IssueMapper;
import com.zmh.entity.Ichange;
import com.zmh.entity.IssueEntity;
import com.zmh.entity.MailEntity;
import com.zmh.service.http.utils.HttpAPIService;
import com.zmh.service.http.utils.HttpResult;
import com.zmh.service.msg.MailService;

/** 
 * Redmine的BUG刷新
 * @author: zhoumh
 * @version: 创建时间：2018年7月24日 下午12:37:04 
 * @Description: 
 */ 
@Service
public class RedmineHttp {
	private static Logger logger = LoggerFactory.getLogger(RedmineHttp.class);
	@Autowired
	private HttpAPIService httpAPIService;
	@Autowired
	private IssueMapper issueMapper;
	@Autowired
	private MailService mailService;
	
//	private static String baseUrl = "http://192.168.8.20:88";
	private static String baseUrl = "http://60.213.47.147:50000";
	
	/*
	 * 模拟登陆，刷新我的工作台
	 * 获取指派给我的工作内容，与数据库中已存在的工作ID匹配
	 * redmine的authenticity_token是存在header的meta属性里面的
	 */
	public void getIssues() throws Exception{
		
		//打开指派给我的任务
		String html = httpAPIService.doGet(baseUrl+"/redmine/issues?query_id=140");
		Document doc = Jsoup.parse(html);
		//判断是否需要登录
		Elements links = login(doc.select("tr.issue"));
		List<IssueEntity> issues = new ArrayList<>();
		for (Element element : links) {
			String rid = element.select("td.id>a").text();
			String subject = element.select("td.subject>a").text();
			String author = element.select("td.author>a").text();
			String assigned = element.select("td.assigned_to>a").text();
			String project = element.select("td.project>a").text();
			String status = element.select("td.status").text();
			String tracker = element.select("td.tracker").text();
			String created = element.select("td.created_on").text();
			String updated = element.select("td.updated_on").text();
			IssueEntity issue = new IssueEntity(rid, subject, author, assigned, project, status, tracker, created, updated);
			issues.add(issue);
		}
		for (IssueEntity issue : issues) {
			//使用rid查询，能够查询到，判断updated是否一致，如果不一致就是有修改。查询不到，就新增。
			IssueEntity temp = issueMapper.getOneByRid(issue.getRid());
			String title = "收到问题： #"+issue.getRid();
			String content = "";
			//生成邮件内容
			content = content.concat("问题： #"+issue.getRid());
			content = content.concat("\n类型："+issue.getTracker());
			content = content.concat("\n状态："+issue.getStatus());
			content = content.concat("\n创建人："+issue.getAuthor());
			content = content.concat("\n创建时间："+issue.getCreated());
			content = content.concat("\n修改时间："+issue.getUpdated());
			content = content.concat("\n标题："+issue.getSubject()+"\n\n");
			if (null == temp) {
				//增加问题信息
				issueMapper.insert(issue);
				//如果新增的问题创建时间与修改时间不一致，就获取最后转发人信息
				if (!issue.getCreated().equals(issue.getUpdated())) {
					content = content.concat(getHistory(issue.getRid()));
				}
			}else{
				//数据库已存在的问题
				String updated = temp.getUpdated();
				//网页获取的问题
				String tupdated = issue.getUpdated()+":00";
				if (!tupdated.equals(updated.substring(0, updated.lastIndexOf(".")))) {
					issue.setUpdateTime(DateUtil.getDateTime());
					//更新问题
					issueMapper.update(issue);
					//获取历史记录
					content = content.concat(getHistory(issue.getRid()));
				}else{
					//问题已存在，且没有更新，跳过循序不发邮件
					continue;
				}
			}
			mailService.saveMail(new MailEntity("Redmine提醒<zhoumh1985@qq.com>", "zmh1812@qq.com", title, content,"sendSimpleMail"));
		}
		logger.info("已完成本次redmine刷新。");
	}
	
	public Elements login(Elements es) throws Exception{
		if (es.size()>0) {
			return es;
		}
		String html = httpAPIService.doGet(baseUrl+"/redmine/login");
		Document doc = Jsoup.parse(html);
		String authenticity_token = doc.select("meta[name=csrf-token]").attr("content");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("utf8", "✓");
		map.put("login", "登录 »");
		map.put("username", "zmh");
		map.put("password", "zhouminghao");
		map.put("authenticity_token", authenticity_token);
		map.put("back_url", baseUrl+"/redmine/");
		// 登录
		HttpResult result = httpAPIService.doPost(baseUrl+"/redmine/login",map);
		if (result.getCode()==302&&result.getBody().indexOf("redirected")>-1) {
			logger.info("Redmine登录成功！");
		}
		//重新查询
		return Jsoup.parse(httpAPIService.doGet(baseUrl+"/redmine/issues?query_id=140")).select("tr.issue");
	}
	
	//获取问题转发过程
	private String getHistory(String id) throws Exception{
		//进入问题详细页面，查找问题最后指派人和指派内容
		Document cdoc = Jsoup.parse(httpAPIService.doGet(baseUrl+"/redmine/issues/"+id));
		Elements history = cdoc.select("div.journal.has-details");
		//问题详细描述
		String content = HtmlUtil.delHTMLTag(cdoc.select("div.description > div.wiki > p").toString().replaceAll("<br>", " \n "))+"\n\n";
		//问题处理过程
		for (Element e : history) {
			String user = e.select("h4 > a.user.active").text(); //问题变更人
			String created = e.select("h4 > a[href^=/redmine/projects]").attr("title"); //变更时间
			String details = HtmlUtil.delHTMLTag(e.select("ul.details").toString()); //变更记录
			String context = HtmlUtil.delHTMLTag(e.select("div.wiki > p").toString()); //变更内容
			String description = e.attr("id").replace("change-", "");
			Ichange ichange = new Ichange(id, user, details, context, created,description);
			if (issueMapper.getOneBydesc(description)==null) {
				//判断变更记录不存在就增加
				issueMapper.insertChange(ichange);
			}
			content = content.concat("由 "+user+" 更新于 ");
			content = content.concat(created+"\n");
			content = content.concat(details+"\n");
			content = content.concat(context+"\n\n");
		}
		return content;
	}
}
